package com.zh.kotlin_mvvm.ui

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import com.flyco.tablayout.listener.CustomTabEntity
import com.flyco.tablayout.listener.OnTabSelectListener
import com.zh.common.base.BaseActivity
import com.zh.kotlin_mvvm.R
import com.zh.kotlin_mvvm.bean.TabEntity
import com.zh.kotlin_mvvm.databinding.ActivityScrollViewTabBinding

class ScrollViewTabActivity : BaseActivity<ActivityScrollViewTabBinding>() {

    private var scrollviewFlag = false //标记是否是scrollview引起的滑动

    @SuppressLint("ClickableViewAccessibility", "NewApi")
    override fun initView(savedInstanceState: Bundle?) {
        val tabList = ArrayList<CustomTabEntity>()
        tabList.add(TabEntity("tab1"))
        tabList.add(TabEntity("tab2"))
        tabList.add(TabEntity("tab3"))
        viewBinding.cTabLayout.setTabData(tabList)

        viewBinding.cTabLayout.setOnTabSelectListener(object : OnTabSelectListener {
            override fun onTabSelect(position: Int) {
                when (position) {
                    0 -> viewBinding.scrollView.smoothScrollTo(0, viewBinding.test1.top)
                    1 -> viewBinding.scrollView.smoothScrollTo(0, viewBinding.test2.top)
                    2 -> viewBinding.scrollView.smoothScrollTo(0, viewBinding.test3.top)
                }
                scrollviewFlag = false
            }

            override fun onTabReselect(position: Int) {
            }
        })

        viewBinding.scrollView.setOnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_DOWN) {
                scrollviewFlag = true
            }
            false
        }
        viewBinding.scrollView.setOnScrollChangeListener { v, _, scrollY, _, _ ->
            if (scrollviewFlag) {
                val isBottom =
                    viewBinding.scrollView.getChildAt(0).height == scrollY + viewBinding.scrollView.height - viewBinding.scrollView.paddingTop - viewBinding.scrollView.paddingBottom
                when {
                    (scrollY < viewBinding.test2.top) and (viewBinding.cTabLayout.currentTab != 0) -> {
                        viewBinding.cTabLayout.currentTab = 0
                    }
                    (scrollY >= viewBinding.test2.top) and (scrollY < viewBinding.test3.top) and (viewBinding.cTabLayout.currentTab != 1) -> {
                        viewBinding.cTabLayout.currentTab = 1
                    }
                    ((scrollY >= viewBinding.test3.top) or isBottom) and (viewBinding.cTabLayout.currentTab != 2) -> {
                        viewBinding.cTabLayout.currentTab = 2
                    }
                }
            }
        }
    }
}